package com.aisino.efence.utils;


import net.jpountz.lz4.LZ4Compressor;
import net.jpountz.lz4.LZ4Factory;
import net.jpountz.lz4.LZ4FastDecompressor;
import net.jpountz.lz4.LZ4SafeDecompressor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author wkq
 * @package com.aisino.efence.utils.Lz4Util
 * @create 2018-04-12 13:12
 **/
public class Lz4Util {

    private static final Logger LOG = LoggerFactory.getLogger(Lz4Util.class);

    /**
     * lz4压缩后返回 InputStream
     *
     * @param bytes
     * @return
     */
    public static InputStream compressor(byte[] bytes) {
        LZ4Factory factory = LZ4Factory.fastestInstance();
        final int decompressedLength = bytes.length;
        System.out.println(decompressedLength);
        LZ4Compressor compressor = factory.fastCompressor();
        int maxCompressedLength = compressor.maxCompressedLength(decompressedLength);
        byte[] compressed = new byte[maxCompressedLength];
        compressor.compress(bytes, 0, decompressedLength, compressed,
                0, maxCompressedLength);
        return new ByteArrayInputStream(compressed);
    }

    /**
     * lz4解压缩后返回 InputStream
     *
     * @param is
     * @return
     */
    public static byte[] decompressed(InputStream is, int oriFileLength) {
        LZ4Factory factory = LZ4Factory.fastestInstance();
        try {
            LZ4FastDecompressor decompressed = factory.fastDecompressor();
            byte[] restored = new byte[oriFileLength];
            decompressed.decompress(inputStreamToBytes(is), 0, restored, 0, oriFileLength);
            return restored;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    private static byte[] inputStreamToBytes(InputStream is) throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = is.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        return swapStream.toByteArray();
    }
}
